<template>
  <div class="document-container">
    <div class="header">
      <div class="granary-info">
        <div class="granary-header">
          <el-avatar :size="64" :src="granaryForm.avatar" v-if="granaryForm.avatar">
            <img src="@/assets/icon/granary.png" />
          </el-avatar>
          <div class="granary-title">
            <el-input
              v-model="granaryForm.name"
              placeholder="请输入知识库名称"
              class="name-input"
            />
            <div class="granary-tags">
              <el-tag v-for="tag in granaryForm.tags" :key="tag" size="small" class="tag">
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </div>
        <p class="description">{{ granaryForm.description }}</p>
        <div class="build-types">
          <span class="label">构建类型：</span>
          <el-checkbox-group v-model="granaryForm.options.buildTypes" disabled>
            <el-checkbox label="knowledge_graph">知识图谱</el-checkbox>
            <el-checkbox label="knowledge_summary">知识总结</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <div class="divider"></div>
      <p class="sub-description">知识库的所有文件都在这里显示，整个知识库都可以链接到 Dify 引用或通过 Chat 插件进行索引。</p>
    </div>

    <el-table :data="documents" style="width: 100%">
      <el-table-column type="index" label="#" width="50" />
      <el-table-column prop="fileName" label="文件名">
        <template #default="scope">
          <div class="file-name">
            <i class="el-icon-document"></i>
            {{ scope.row.fileName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="wordCount" label="字符数" width="120" />
      <el-table-column prop="callCount" label="召回次数" width="120" />
      <el-table-column prop="uploadTime" label="上传时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.status === 'available'">
            可用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-switch v-model="scope.row.enabled" />
          <el-dropdown>
            <span class="el-dropdown-link">
              <i class="el-icon-more"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>编辑</el-dropdown-item>
                <el-dropdown-item>删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store/user'
import { GetGranaryRequest,ListGranariesRequest, ListGranariesResponse, Granary } from '@/types/proto/api/v1/granary_service'
import { Resource, GetResourceRequest } from '@/types/proto/api/v1/resource_service'
import { ListResources, GetResource } from "@/api/resource";
import { GetGranary } from "@/api/granary";
const documents = ref<Resource[]>([])
const searchQuery = ref('')
const userStore = useUserStore()
const granary = ref<Granary | null>(null)

interface GranaryForm {
  name: string
  description: string
  avatar: string
  tags: string[]
  options: { [key: string]: string }
  sources: string[]
  currentGranay: Granary|null,
}

const granaryForm = ref<GranaryForm>({
  name: '',
  description: '',
  avatar: '',
  tags: [],
  options: {},
  sources: [],
  currentGranay: null,
})

const loadDocuments = async () => {
    if (granary.value != null) {
        granary.value.sources.forEach(async (source) => {
        let req = {urn:source} as GetResourceRequest
        let res = await GetResource(req)
        documents.value.push(res)
    })
  }
}
const router = useRouter()
const route = useRoute()

const parseParamFromRoute = async () => {
  try {
      console.log("doc parse param")
      const urn = route.query.granary
      let reload = true
      console.log("doc granary urn:", urn)
      if (urn === null || urn === undefined) {
          granary.value = null
          reload = false
      } else if (granary.value != null) {
          if (granary.value.urn === urn) {
              console.log("no need to reload")
              reload = false
          }
      }

      if (reload) {
          let req = {urn:urn} as GetGranaryRequest
          let res = await GetGranary(req)
          granary.value = res
      }
      userStore.granary = granary.value
      if (granary.value != null) {
        granaryForm.value.currentGranay = granary.value
        granaryForm.value.sources = granary.value.sources
        granaryForm.value.name = granary.value.name
        granaryForm.value.description = granary.value.description
        granaryForm.value.avatar = granary.value.avatar
        granaryForm.value.tags = granary.value.tags
        granaryForm.value.options = granary.value.options
      }
  } catch (error) {
      console.error('Error parsing baidudisk from route:', error)
  }
}

onMounted(() => {
  granary.value = userStore.granary

  parseParamFromRoute().then(() => {
    loadDocuments()
  })
})

</script>

<style scoped lang="scss">
.document-container {
  padding: 20px;
}

.header {
  margin-bottom: 24px;
}

.granary-info {
  margin-bottom: 20px;
}

.granary-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
}

.granary-title {
  .name-input {
    margin-bottom: 8px;
    
    :deep(.el-input__inner) {
      font-size: 1.5em;
      font-weight: bold;
      padding: 0;
      border: none;
      background: transparent;

      &:disabled {
        color: inherit;
      }
      
      &:focus {
        border: 1px solid #dcdfe6;
        padding: 0 8px;
      }
    }
  }
}

.granary-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;

  .tag {
    margin-right: 4px;
  }
}

.build-types {
  margin-top: 12px;
  display: flex;
  align-items: center;
  gap: 8px;

  .label {
    color: #606266;
  }
}

.divider {
  height: 1px;
  background-color: #e4e7ed;
  margin: 16px 0;
}

.sub-description {
  margin: 8px 0 16px;
}

.description {
  color: #666;
  margin: 8px 0 16px;
}

.search-bar {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.add-button {
  white-space: nowrap;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-dropdown-link {
  cursor: pointer;
  margin-left: 12px;
}
</style>
